package org.tloss.web.editor.enity.editors;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.layout.TreeColumnLayout;
import org.eclipse.jface.viewers.ColumnLabelProvider;
import org.eclipse.jface.viewers.ColumnWeightData;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.swt.widgets.TreeColumn;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.model.WorkbenchContentProvider;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.part.EditorPart;
import org.tloss.web.editor.Utils;
import org.tloss.web.editor.database.editors.jdbc.Column;
import org.tloss.web.editor.database.editors.jdbc.Table;

public class MappingEditor extends EditorPart implements IResourceChangeListener {
	Table table = null;
	ColumnAdaptableList adaptableList = new ColumnAdaptableList();

	public Table getDatabase() {
		return table;
	}

	private boolean dirty = false;
	TreeViewer treeViewer;

	public void doSave(IProgressMonitor monitor) {
		IEditorInput editorInput = this.getEditorInput();
		IFileEditorInput fileEditorInput = (IFileEditorInput) editorInput;
		IFile file = fileEditorInput.getFile();
		JAXBContext context;
		try {
			context = JAXBContext.newInstance(Table.class);
			Marshaller marshaller = context.createMarshaller();
			ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
			marshaller.marshal(table, arrayOutputStream);

			file.setContents(
					new ByteArrayInputStream(arrayOutputStream.toByteArray()),
					false, true, monitor);
			this.dirty = false;
			this.firePropertyChange(IEditorPart.PROP_DIRTY);
		} catch (JAXBException e) {
			Utils.logError("Can't save enity", e);
		} catch (CoreException e) {
			Utils.logError("Can't save enity", e);

		}

	}

	public void doSaveAs() {

	}

	public void init(IEditorSite site, IEditorInput input)
			throws PartInitException {
		if (!(input instanceof IFileEditorInput)) {
			throw new PartInitException("Input must be a file");
		}
		setSite(site);
		setInput(input);
		IFileEditorInput editorInput = (IFileEditorInput) input;
		IFile file = editorInput.getFile();
		JAXBContext context;
		InputStream inputStream  =null;
		try {
			inputStream = file.getContents();
			if (inputStream.available() == 0) {
				throw new PartInitException("Can't load resource");
			} else {
				context = JAXBContext.newInstance(Table.class);
				Unmarshaller marshaller = context.createUnmarshaller();
				table = (Table) marshaller.unmarshal(inputStream);
				List<Column> columns = table.getColumns();
				if (columns != null) {
					for (int i = 0; i < columns.size(); i++) {
						adaptableList.add(new ColumnElement(columns.get(i),
								this));
					}
				}
			}
		} catch (CoreException e) {
			Utils.logError("Can't load resource", e);
			throw new PartInitException("Can't load resource", e);
		} catch (JAXBException e) {
			Utils.logError("Can't load resource", e);
			throw new PartInitException("Can't load resource", e);
		} catch (IOException e) {
			Utils.logError("Can't load resource", e);
			throw new PartInitException("Can't load resource", e);
		}finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (IOException e) {
				Utils.logError("Can't close input stream", e);
			}
		}
	}

	public boolean isDirty() {

		return dirty;
	}

	public boolean isSaveAsAllowed() {

		return false;
	}

	public void createPartControl(Composite parent) {
		Composite composite = new Composite(parent, SWT.NONE);
		GridLayout layout = new GridLayout();
		composite.setLayout(layout);
		layout.numColumns = 2;

		Composite treeContainer = new Composite(composite, SWT.BORDER);
		GridData gridData = new GridData();
		treeContainer.setLayoutData(gridData);
		gridData.horizontalAlignment = SWT.FILL;
		gridData.grabExcessHorizontalSpace = true;
		gridData.verticalAlignment = SWT.FILL;
		gridData.grabExcessVerticalSpace = true;
		TreeColumnLayout treeLayout = new TreeColumnLayout();
		treeContainer.setLayout(treeLayout);
		treeViewer = new TreeViewer(treeContainer, SWT.MULTI
				| SWT.FULL_SELECTION);
		Tree tree = treeViewer.getTree();
		tree.setHeaderVisible(true);

		TreeColumn valueColumn;
		valueColumn = new TreeColumn(tree, SWT.NONE);
		valueColumn.setText("Value");
		treeLayout.setColumnData(valueColumn, new ColumnWeightData(2));

		treeViewer.setContentProvider(new WorkbenchContentProvider());
		// final DatabaseConfigLableProvider treeLabelProvider = new
		// DatabaseConfigLableProvider();
		final WorkbenchLabelProvider labelProvider = new WorkbenchLabelProvider();
		treeViewer.setLabelProvider(new WorkbenchLabelProvider());

		TreeViewerColumn column2 = new TreeViewerColumn(treeViewer, valueColumn);
		column2.setLabelProvider(new ColumnLabelProvider() {
			public String getText(Object element) {
				return labelProvider.getText(element);
			}

			public Image getImage(Object element) {

				return labelProvider.getImage(element);
			}
		});

		getSite().setSelectionProvider(treeViewer);

		treeViewer.setInput(adaptableList);

		treeViewer.setAutoExpandLevel(TreeViewer.ALL_LEVELS);

		/*Composite wrapper = new Composite(composite, SWT.NONE);
		RowLayout rowLayout = new RowLayout();
		wrapper.setLayout(rowLayout);
		rowLayout.type = SWT.VERTICAL;

		final Button button = new Button(wrapper, SWT.NONE);
		button.setText("Test connection");

		button.addMouseListener(new MouseListener() {

			public void mouseUp(MouseEvent e) {

			}

			public void mouseDown(MouseEvent e) {

			}

			public void mouseDoubleClick(MouseEvent e) {

			}
		});*/
	}

	public void setFocus() {

	}
	@Override
	public void resourceChanged(IResourceChangeEvent arg0) {
		dirty = true;
		firePropertyChange(IEditorPart.PROP_DIRTY);
	}

}
